package com.shuyun.concurrent;

/**
 * @description:
 * @author: shuai.chen@shuyun.com
 * @date: 2023/1/16 4:17 PM
 */
public class VisibilityTest {
    public static void main(String[] args) {
        ChangeThread thread = new ChangeThread();
        thread.start();
        while (true) {
            if (thread.flag) { // B
                System.out.println("Finished");
                return;
            }
        }
    }

    public static class ChangeThread extends Thread {
        /**
         * 不加 volatile ， main线程 看不到 flag值变化 ，不会打印  Finished
         * 加了 volatile ， main线程 看到 flag值变化， 会打印 Finished
         */
        private  boolean flag = false;

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true; // A
            System.out.println("Change flag = " + flag);
        }
    }
}
